﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net.Sockets;
using SmallERP.MODEL.FoundationModel;
using SmallERP.MODEL;
using System.Drawing;
using SmallERP.DAL;
using SmallERP.MODEL.MakeBigPic;
using System.Windows.Forms;
using SmallERP.COM;
using SmallERP.MODEL.PrintManage;
using System.Data;

namespace SmallERP.HostBll.MakeBigPic
{
    public class MainBLL
    {
        private string _strDogCode = string.Empty;//加密狗的编码，用于加解密
        private const string GETDOGCODE = "GD-0";//传输命令
        private const string SUBAREACODE = "SA-";

        private string _serverIP;
        private int _serverPort;
        private BoardBLL boardBll;
        public MainBLL(string ServerIP, int ServerPort)
        {
            //MessageBox.Show("21");
            _serverIP = ServerIP;
            _serverPort = ServerPort;
            //DAL.AccessHelper.pathdb = Application.StartupPath + @"\smallerp.mdb";
            
            boardBll = new BoardBLL();
            //MessageBox.Show("22");
            boardBll.addr = _serverIP;
            boardBll.port = _serverPort;
            //DAL.AccessHelper.pathdb = Application.StartupPath + @"\smallerp.mdb";
            //获得加密狗的ID号用于解密
            //_strDogCode = GetDogCode();
        }

        //获得加密狗的ID号用于解密
        private string GetDogCode()
        {
            string strResult = string.Empty;
            byte[] myReadBuffer = new byte[1024];
            //string addr = ConfigurationManager.AppSettings["RemoteIP"].ToString();
            //int port = Convert.ToInt32(ConfigurationManager.AppSettings["RemotePort"]);
            string addr = _serverIP;
            int port = _serverPort;

            string RedStrResult = string.Empty;
            TcpClient client = new TcpClient();
            NetworkStream net = null;

            try
            {
                client.Connect(addr, port);
                client.SendTimeout = 60 * 1000;
                client.ReceiveTimeout = 60 * 1000;
                net = client.GetStream();
                net.ReadTimeout = 60 * 1000;

                byte[] myWriteBuffer = Encoding.Unicode.GetBytes(GETDOGCODE);

                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);

                int tryNum = 0;//只试三次

                while (tryNum < 3)
                {
                    int redLenth=0;
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {
                        //return -2;//读取失败
                        strResult= string.Empty;
                        break;
                    }

                    if (redLenth > 0)
                    {
                        strResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        break;
                    }
                    tryNum++;

                }
                net.Close();
                return strResult;
            }
            catch (Exception)
            {
                return string.Empty;
            }
            finally
            {
                client.Close();
                if (net != null)
                {
                    net.Close();
                    net.Dispose();
                }

            }
        }

        /// <summary>
        /// 向加密狗写入平米数
        /// </summary>
        /// <param name="areas">本次大板的平米数</param>
        /// <returns>0:代表成功，-1：-2：代余下的平米数不足,-3:代表与服务器连接异常 </returns>
        public int SubArea(float areas)
        {
            int result = 0;
            string strResult = string.Empty;
            byte[] myReadBuffer = new byte[1024];
            string addr = _serverIP;
            int port = _serverPort;

            string RedStrResult = string.Empty;
            TcpClient client = new TcpClient();
            NetworkStream net = null;

            try
            {
                client.Connect(addr, port);
                client.SendTimeout = 60 * 1000;
                client.ReceiveTimeout = 60 * 1000;
                net = client.GetStream();
                net.ReadTimeout = 60 * 1000;

                byte[] myWriteBuffer = Encoding.Unicode.GetBytes(SUBAREACODE + areas);

                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);

                int tryNum = 0;//只试三次

                while (tryNum<3)
                {
                    int redLenth=0;
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {                     
                        result= - 3;
                        break;
                    }

                    if (redLenth > 0)
                    {
                        strResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        break;
                    }
                    tryNum++;
                }
                net.Close();

                result= Convert.ToInt32(strResult);//
            }
            catch (Exception)
            {
                result= - 3;
            }
            finally
            {
                client.Close();
                if (net != null)
                {
                    net.Close();
                    net.Dispose();
                }

            }

            return result;
        }

        /// <summary>
        /// -2代表连联解密的服务器不同，-1解密有错,1正常
        /// </summary>
        /// <param name="b"></param>
        /// <returns>-5:找不到加密狗，-2代表解密出错,-4代表没有可生成的大图</returns>
        public int GetOneBoard(out BoardInfo_MakeBigPic b)
        {
            b = new BoardInfo_MakeBigPic();
            //if (string.IsNullOrEmpty(_strDogCode))
            //{
            //    _strDogCode = GetDogCode();
            //    if (string.IsNullOrEmpty(_strDogCode))
            //    {
            //        return -5;
            //    }
            //}

            int result = 1;
            //BoardBLL boardBll = new BoardBLL();
            //boardBll.addr = _serverIP;
            //boardBll.port = _serverPort;

            try
            {
                b = boardBll.GetOneBoardToProduct();
            }
            catch (Exception)
            {
                return -5;
            }
           
       

            if (b == null)//没有可用的格子
            {
                return -4;
            }
            //int a = DecryPtPointAtLocalNew(b);
            //if (a == -1)
            //{
            //    return -5;
            //}
         
            return result;
        }
        //LayoutDll.ClassInterFace InterFace = new LayoutDll.ClassInterFace();
        int DecryPtPointAtLocalNew(BoardInfo_MakeBigPic b)
        {
            //int rtnInt = 0;
            //PhotoInfo_MakeBigPic bm = b.PhotoS.OrderByDescending(p => p.BasePhotoInfo.PhotoId).FirstOrDefault();
            //pm.Location = new Point(Convert.ToInt32(pm.X), Convert.ToInt32(pm.Y));
            ////bm.X = InterFace.Function2(bm.X);
            //foreach (PhotoInfo_MakeBigPic pm in b.PhotoS)
            //{
            //    try
            //    {
            //        pm.Location = new Point(Convert.ToInt32(pm.X), Convert.ToInt32(pm.Y));
            //    }
            //    catch (Exception FX)
            //    {
            //        try
            //        {
            //            pm.Location = new Point(Convert.ToInt32(InterFace.Function2(pm.X)), Convert.ToInt32(pm.Y));
            //        }
            //        catch (Exception ex)
            //        {
            //            SetBoardStatus(b.BoardBaseInfo.BoardId, (int)SmallERP.COM.Status.EnumBoardStatus.Error, "加载照片坐标出错");
            //            rtnInt = 0;
            //        }
            //    }

            //}
            //try
            //{
            //b.PhotoS.ForEach(p => p.Location = new Point(Convert.ToInt32(p.X), Convert.ToInt32(p.Y)));
            //}catch
            //{
            //    SetBoardStatus(b.BoardBaseInfo.BoardId, (int)SmallERP.COM.Status.EnumBoardStatus.Error, "加载照片坐标出错,请退版重新拼");
            //    rtnInt = 0;
            //}
            return 0;

        }
        //选将坐标解密
        public int DecryPtPoint(BoardInfo_MakeBigPic Board)
        {
            byte[] myReadBuffer = new byte[5120];
            string addr = _serverIP;
            int port = _serverPort;


            string RedStrResult = string.Empty;
            TcpClient client = new TcpClient();
            NetworkStream net = null;
            try
            {
                //int reCount = 0;
                client.Connect(addr, port);
                client.SendTimeout = 60 * 1000;
                client.ReceiveTimeout = 60 * 1000;
                net = client.GetStream();
                net.ReadTimeout = 60 * 1000;

                byte[] myWriteBuffer = Encoding.Unicode.GetBytes(Board.BoardBaseInfo.BoardId.ToString());

                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);
                int tryNum = 0;//只试三次

                while (tryNum < 3)
                {
                    //if (reCount>=4)//重试三次不行就退出
                    //{
                    //    break;
                    //}
                    int redLenth;
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {
                        return -2;
                    }

                    if (redLenth > 0)
                    {
                        RedStrResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        break;
                    }
                    tryNum++;

                }
                net.Close();

            }
            catch (Exception)
            {
                return -1;
            }
            finally
            {

                client.Close();
                if (net != null)
                {
                    net.Close();
                    net.Dispose();
                }

            }

            if (!string.IsNullOrEmpty(RedStrResult))
            {
                //分解字符串开如 picmakeupId○x值 ○y值 ¤13○353456346○lksldflsldf
                try
                {
                    string[] picStr = RedStrResult.Split(new char[] { '¤' });
                    foreach (string strPic in picStr)
                    {
                        if (string.IsNullOrEmpty(strPic))
                        {
                            continue;
                        }
                        string[] strT = strPic.Split(new char[] { '○' });
                        int picMarkUpId = Convert.ToInt32(strT[0]);
                        int X = Convert.ToInt32(strT[1]);
                        int Y = Convert.ToInt32(strT[2]);

                        var pi = Board.PhotoS.First(p => p.PmID == picMarkUpId);
                        if (pi != null)
                        {
                            pi.Location = new Point(X, Y);
                        }
                    }
                }
                catch (Exception)
                {

                    return -2;
                }

                return 1;
            }
            return -1;
        }


        /*
        const int MIN_ASC = 32;
        const int MAX_ASC = 126;
        const int NUM_ASC = 95;
        //解密
        public string Decipher(string strFromText)
        {
            StringBuilder result = new StringBuilder();
            char[] random = _strDogCode.ToCharArray();
            char[] from_text = strFromText.ToCharArray();
            char[] buf1 = new char[10];
            int offset;
            int str_len = 1;
            int i;
            int ch;

            str_len = from_text.Length;

            for (i = 0; i < str_len; i++)
            {
                ch = (int)from_text[i];
                if (ch >= MIN_ASC && ch <= MAX_ASC)
                {
                    ch = ch - MIN_ASC;
                    offset = (NUM_ASC + 1) * random[i];
                    ch = (ch - offset) % NUM_ASC;
                    if (ch < 0)
                    {
                        ch = ch + NUM_ASC;
                    }
                    ch = ch + MIN_ASC;
                    buf1[i] = (char)ch;
                }
                else
                {
                    buf1[i] = from_text[i];
                }
            }
            foreach (var item in buf1)
            {
                result.Append(item);
            }
            return result.ToString();
        }
       
        public int DecryPtPointAtLocal(BoardInfo_MakeBigPic Board)
        {
            try
            {
                foreach (var pi in Board.PhotoS)
                {
                    //pi.Location = new Point(Convert.ToInt32(Decipher(pi.X)), Convert.ToInt32(Decipher(pi.Y)));
                    //pi.Location = new Point(Convert.ToInt32(pi.X), Convert.ToInt32(pi.Y));
                }
            }
            catch (Exception)
            {
                return -2;
            }
            finally
            {
                //将此板
            }
            return 1;
        }
     
        //远程选将从标解密
       
        public int DecryPtPoint(BoardInfo_ProductBigPic Board)
        {
            byte[] myReadBuffer = new byte[5120];
            string addr = ConfigurationManager.AppSettings["RemoteIP"].ToString();
            int port = Convert.ToInt32(ConfigurationManager.AppSettings["RemotePort"]);


            string RedStrResult = string.Empty;
            TcpClient client = new TcpClient();
            NetworkStream net = null;
            try
            {
                //int reCount = 0;
                client.Connect(addr, port);
                client.SendTimeout = 60 * 1000;
                client.ReceiveTimeout = 60 * 1000;
                net = client.GetStream();
                net.ReadTimeout = 60 * 1000;

                byte[] myWriteBuffer = Encoding.Unicode.GetBytes(Board.BoardBaseInfo.BoardId.ToString());

                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);

                while (true)
                {
                    //if (reCount>=4)//重试三次不行就退出
                    //{
                    //    break;
                    //}
                    int redLenth;
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {
                        return -2;
                    }

                    if (redLenth > 0)
                    {
                        RedStrResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        break;
                    }
                    //reCount++;

                }
                net.Close();

            }
            catch (Exception)
            {
                return -1;
            }
            finally
            {

                client.Close();
                if (net != null)
                {
                    net.Close();
                    net.Dispose();
                }

            }

            if (!string.IsNullOrEmpty(RedStrResult))
            {
                //分解字符串开如 picmakeupId○x值 ○y值 ¤13○353456346○lksldflsldf
                string[] picStr = RedStrResult.Split(new char[] { '¤' });
                foreach (string strPic in picStr)
                {
                    if (string.IsNullOrEmpty(strPic))
                    {
                        continue;
                    }
                    string[] strT = strPic.Split(new char[] { '○' });
                    int picMarkUpId = Convert.ToInt32(strT[0]);
                    int X = Convert.ToInt32(strT[1]);
                    int Y = Convert.ToInt32(strT[2]);

                    var pi = Board.ListPhotos.First(p => p.PicMakeUpId == picMarkUpId);
                    if (pi != null)
                    {
                        pi.Location = new Point(X, Y);
                    }
                }
                return 1;
            }
            return -1;
        }
        */
        /// <summary>
        /// 生成大图成功后更改大图的状态以及照片的状态还有流程的状态
        /// </summary>
        /// <param name="p"></param>
        /// <param name="p_2"></param>
        /// <returns>1:代表正常,-1:大板存在，-2：照片不存在；-3：执行操作时出错</returns>
        public int MakeBigPicSusscess(BoardInfo_MakeBigPic board)
        {
            int result = 1;
            if (board != null)
            {
                //BoardBLL _mainDal = new BoardBLL();         
                result = boardBll.MakeBigPicSusscess(board);
            }
            else
            {
                result = -1;//参数不正确
            }
            return result;
        }

       public void ReNameBoardPath(int inBoardid,string inPath)
       {
           boardBll.ReNameBoardPath(inBoardid, inPath);
       }
        public void DeleteBoards(List<int> boardids)
        {
            boardBll.DeleteBoards(boardids);
        }
        public void ReProduct(List<int> boardids)
        {
            boardBll.ReProduct(boardids);
        }
        public int SetBoardStatus2(int boardId, int boardStatus, string remark)
        {
            //MainDAL _mainDal = new MainDAL();
            //_mainDal.SetBoardStatus(boardId, boardStatus, remark);
            return BoardBLL.UpdateBoard2(boardId, boardStatus, remark);
        }
        public void SetBoardStatus(int boardId, int boardStatus, string remark)
        {
            //MainDAL _mainDal = new MainDAL();
            //_mainDal.SetBoardStatus(boardId, boardStatus, remark);
            BoardBLL.UpdateBoard(boardId, boardStatus, remark);
        }
        public void UpdateBoardPoint(int inBoardid, string inStr)
        {
            //using (smallerpDataContext db = new smallerpDataContext())
            //{
            //    Board b = db.Board.FirstOrDefault(bd => bd.BoardId == inBoardid);
            //    if (b != null)
            //    {
            //        b.AutoPoint = inStr;

            //    }
            //    db.SaveChanges();
 
            //}
            string UpdateBoardStr = "update board set AutoPoint='" + inStr + "' where boardid=" + inBoardid;
            AccessHelper.ExecuteNonQuery(UpdateBoardStr);
        }
        public List<BoardModel> GetErrorList()
        {
            string QueryBoardinfo;
            DataTable tableBoard;
            int Errorstatus = (int)SmallERP.COM.Status.EnumBoardStatus.Error;
            QueryBoardinfo = " select AutoPoint,BoardId,CreateTime,DPI,Height,LastPrintTime,Length,board.PaperFaceId,PaperFaceName,board.PaperTypeId,PaperTypeName,PicPath,PrinterId,PrintNum,PrintPaperId,PrintPriority,Remark,Status,WasteRate from board,papertype,paperface where board.papertypeid=papertype.papertypeid and board.paperfaceid=paperface.paperfaceid  and status=" + Errorstatus + " order by PrintPriority desc,CreateTime";

            tableBoard = AccessHelper.dataTable(QueryBoardinfo);

            return MappingBoardToModel(tableBoard, 1);
        }
        private List<BoardModel> MappingBoardToModel(DataTable tableBoard, int measureUnit)
        {
            List<BoardModel> list = new List<BoardModel>();
            for (int i = 0; i < tableBoard.Rows.Count; i++)
            {
                BoardModel board = new BoardModel()
                {
                    AutoPoint = Convert.ToString(tableBoard.Rows[i]["AutoPoint"]),
                    BoardId = Convert.ToInt32(tableBoard.Rows[i]["BoardId"]),
                    CreateTime = Convert.ToDateTime(tableBoard.Rows[i]["Createtime"]),
                    DPI = Convert.ToInt32(tableBoard.Rows[i]["DPI"]),
                    Height = Convert.ToInt32(tableBoard.Rows[i]["Height"]),
                    LastPrintTime = Convert.ToDateTime(tableBoard.Rows[i]["LastPrintTime"]),
                    Length = Convert.ToInt32(tableBoard.Rows[i]["Length"]),
                    PaperFaceId = Convert.ToInt32(tableBoard.Rows[i]["PaperFaceId"]),
                    PaperFaceName = Convert.ToString(tableBoard.Rows[i]["PaperFaceName"]),
                    PaperTypeId = Convert.ToInt32(tableBoard.Rows[i]["PaperTypeId"]),
                    PaperTypeName = Convert.ToString(tableBoard.Rows[i]["PaperTypeName"]),
                    PicPath = Convert.ToString(tableBoard.Rows[i]["PicPath"]),
                    PrinterId = Convert.ToInt32(tableBoard.Rows[i]["PrinterId"]),
                    PrintNum = Convert.ToInt32(tableBoard.Rows[i]["PrintNum"]),
                    PrintPaperId = Convert.ToInt32(tableBoard.Rows[i]["PrintPaperId"]),
                    PrintPriority = Convert.ToInt32(tableBoard.Rows[i]["PrintPriority"]),
                    Remark = Convert.ToString(tableBoard.Rows[i]["Remark"]),
                    Status = Convert.ToInt32(tableBoard.Rows[i]["Status"]),
                    WasteRate = Convert.ToDouble(tableBoard.Rows[i]["WasteRate"])

                };
                switch (measureUnit)
                {
                    case (int)Status.MeasureUnit.Inch:
                        board.BoardArea = Math.Round((double)(board.Height / board.DPI * board.Length / board.DPI), 4);
                        board.widthView = Math.Round((double)board.Height / board.DPI, 2);
                        board.LengthView = Math.Round((double)board.Length / board.DPI, 2);
                        break;
                    case (int)Status.MeasureUnit.Cm:
                        board.BoardArea = Math.Round((double)(board.Height / board.DPI * 2.54 * board.Length / board.DPI * 2.54), 4);
                        board.widthView = Math.Round((double)board.Height / board.DPI * 2.54, 2);
                        board.LengthView = Math.Round((double)board.Length / board.DPI * 2.54, 2);
                        break;
                    case (int)Status.MeasureUnit.Meter:
                        board.BoardArea = Math.Round((double)(board.Height / board.DPI * 2.54 * board.Length / board.DPI * 2.54 / 10000), 4);
                        board.widthView = Math.Round((double)board.Height / board.DPI * 2.54 / 100, 2);
                        board.LengthView = Math.Round((double)board.Length / board.DPI * 2.54 / 100, 2);
                        break;
                    default:
                        break;
                }

                list.Add(board);
            }
            return list;
        }
    }
}
